from datetime import datetime, timedelta, timezone

import jwt
from fastapi import Depends
from fastapi.security import OAuth2PasswordRequestForm

from config import db_init_config
from holder.context_holder import cache_user, UserVO, get_cached_user
from models.vo.jwt_user_vo import JwtUserVO
from models.dto.register_dto import RegisterDTO
from models.result import Result
from util.toolkit import IdWorker


# 登录接口
def login(form_data: OAuth2PasswordRequestForm = Depends()) -> Result:
    connection = db_init_config.get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = "SELECT * FROM user WHERE username = %s"
            cursor.execute(sql, (form_data.username,))
            user = cursor.fetchone()
            if not user:
                return Result.error(401, "用户名或密码错误")
            if form_data.password != user["password"]:
                return Result.error(401, "用户名或密码错误")
            token = create_access_token(data={"sub": user["username"]})
            uuid = user["id"]
            # 构造 UserVO 对象
            user_vo = UserVO(
                user_id=uuid,
                name=user["username"]
            )
            print("user_vo：" + user_vo.to_json())
            # 缓存用户
            cache_user(user["id"], user_vo)
            cached_user = get_cached_user(uuid)
            print("cached_user：" + cached_user.to_json())
            return Result.ok("登录成功", JwtUserVO(access_token=token, token_type="bearer"))
    except Exception as e:
        return Result.error500(f"登录失败:{str(e)}")  # ✅ 推荐做法：转为字符串

    finally:
        connection.close()


# 注册接口
def register(user: RegisterDTO):
    connection = db_init_config.get_db_connection()
    try:
        with connection.cursor() as cursor:
            # 检查用户名是否已存在
            check_sql = "SELECT COUNT(*) FROM user WHERE username = %s"
            cursor.execute(check_sql, (user.username,))
            result = cursor.fetchone()
            if result and result['COUNT(*)'] > 0:
                return Result.error(400, "用户名已存在")
            # 插入新用户
            insert_sql = "INSERT INTO user (id,username, password) VALUES (%s,%s, %s)"
            cursor.execute(insert_sql, (IdWorker.GetIdStr(), user.username, user.password))
        connection.commit()

        return Result.ok("注册成功")

    except Exception as e:
        connection.rollback()  # 回滚事务
        return Result.error500(f"注册失败: {str(e)}")
    finally:
        connection.close()


SECRET_KEY = "your-secret-key"  # 应配置在环境变量中
ALGORITHM = "HS256"


def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


if __name__ == '__main__':
    access_token = create_access_token(data={"sub": "xq"})
    print(access_token)
